package com.firefly.mq.redisMq.jobhandle;

import com.firefly.mq.redisMq.constants.DelayConfig;
import com.firefly.mq.redisMq.constants.JobStatus;
import com.firefly.mq.redisMq.container.DelayBucket;
import com.firefly.mq.redisMq.container.JobPool;
import com.firefly.mq.redisMq.container.ReadyQueue;
import com.firefly.mq.redisMq.job.DelayJob;
import com.firefly.mq.redisMq.job.Job;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description: 处理日账单
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/10/30
 **/
@Service
@Slf4j
public class BaseQueueCase {
    @Autowired
    private DelayBucket delayBucket;
    @Autowired
    private JobPool jobPool;
    @Autowired
    private ReadyQueue readyQueue;

    public void run(String jobName) {
        try {
            // 拿到任务
            DelayJob delayJob = readyQueue.getJob(jobName);
            if (delayJob != null) {
                Job job = jobPool.getJob(delayJob.getJodId());
                if (job != null) {
                    log.info("任务池内的任务开始执行:" + job.getId());
                    // 这里开始处理任务了
                    if (JobStatus.READY.equals(job.getStatus())) {
                        // 处理成功以后，删除任务，没处理成功，更新为失败，这里可以判断失败次数
                        boolean res = true;
                        if (res) {
                            jobPool.removeDelayJob(job.getId());
                            /*job.setStatus(JobStatus.DELETED);
                            job.setEndAt(LocalDateTime.now());
                            jobPool.addJob(job);*/
                        } else {
                            // 检查失败次数
                            if (job.getRetryCount() < DelayConfig.RETRY_COUNT) {
                                job.setRetryCount(job.getRetryCount() + 1);
                                job.setStatus(JobStatus.RESERVED);
                                jobPool.addJob(job);
                                delayJob.setDelayDate(System.currentTimeMillis() + job.getTtrTime());
                                delayBucket.addDelayJob(delayJob);
                            } else {
                                job.setStatus(JobStatus.FAILED);
                                jobPool.addJob(job);
                            }
                        }
                    }
                }
                // 处理完成以后移除
                readyQueue.popJob(jobName);
            }
        } catch (Exception e) {
            log.error("任务池内的任务开始执行出错：" + e);
        }
    }
}
